export function getBase64(url, callback) {
  //通过构造函数来创建的 img 实例，在赋予 src 值后就会立刻下载图片，相比 createElement() 创建 <img> 省去了 append()，也就避免了文档冗余和污染
  var Img = new Image(),
    dataURL = "";
  Img.src = url + "?v=" + Math.random(); // 处理缓存,fix缓存bug,有缓存，浏览器会报错;
  Img.setAttribute("crossOrigin", "Anonymous"); // 解决控制台跨域报错的问题
  Img.onload = function() {
    //要先确保图片完整获取到，这是个异步事件
    var canvas = document.createElement("canvas"), //创建canvas元素
      width = Img.width, //确保canvas的尺寸和图片一样
      height = Img.height;
    canvas.width = width;
    canvas.height = height;
    canvas.getContext("2d").drawImage(Img, 0, 0, width, height); //将图片绘制到canvas中
    dataURL = canvas.toDataURL("image/jpeg"); //转换图片为dataURL
    callback ? callback(dataURL) : null; //调用回调函数
  };
}

export function getImgToBase64(url,callback){//将图片转换为Base64
  var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    img = new Image;
  img.crossOrigin = 'Anonymous';
  img.onload = function(){
    canvas.height = img.height;
    canvas.width = img.width;
    ctx.drawImage(img,0,0);
    var dataURL = canvas.toDataURL('image/png');
    callback(dataURL);
    canvas = null;
  };
  img.src = url;
}

export function toBase64(file){  //把图片转成base64编码
    return new Promise(function(resolve,reject){
        let reader=new FileReader();
        let imgResult="";
        reader.readAsDataURL(file);
        reader.onload=function(){
            imgResult=reader.result;
        };
        reader.onerror=function(error){
            reject(error);
        };
        reader.onloadend=function(){
            resolve(imgResult);
        }
    })
}

